<script lang="ts" setup>
import { Card, message } from 'ant-design-vue';
import { ref, toRaw } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { handleOrderdataApi } from '#/api';
import { confirmModal } from '#/components';
import dayjs, { Dayjs } from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import 'dayjs/locale/zh-cn';
import { orderFormSchemas, commonFormConfig } from './schemas';

const record = ref(); // 记录调用modal时传递过来的数据
const action = ref(); // 记录当前操作类型
const gridApi = ref(); // 记录调用时传递过来表格实例

// 默认值
const originalData = {
  orderNo: 'WOSHIJIADE',
  quotationNo: '/',
  clientName: '四川润泰特种气体有限公司',
  clientAddr: '四川省德阳市广汉市连山镇柳埝村7组344号',
  contactPerson: '2',
  contactPhone: '2',
  email: '2',
  sampleName: '2',
  modelSpec: '2',
  quantity: '1瓶',
  sampleProp: null,
  testItems: null,
  specialReq: '/',
  subcontractTest: false,
  sampleHandling: true,
  serviceType: false,
  reportResult: true,
  judgmentRule: ['简单接受的二元判定规则'],
  reportSending: 'Byself',
  invoiceType: 'Noneed',
  remarks: '/',
};

const [BaseForm, BaseFormApi] = useVbenForm({
  ...commonFormConfig,
  ...orderFormSchemas,
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  submitButtonOptions: {
    // 按钮显示文本
    content: '提交',
  },
  wrapperClass: 'grid-cols-12',
});

/* 通过弹窗方式加载当前内容 */
const [VbenModal, modalApi] = useVbenModal({
  // fullscreen: true,  // 默认全屏
  confirmText: '提交',
  draggable: true,
  closeOnPressEscape: false,
  closeOnClickModal: false,

  onOpenChange(isOpen) {
    // 判断是打开还是关闭
    if (!isOpen) {
      return;
    }
    record.value = isOpen ? modalApi.getData()?.record || {} : {};
    action.value = isOpen ? modalApi.getData()?.whichAction || '' : '';
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;

    // 填充表单数据
    const whichData = action.value === 'new' ? originalData.orderNo : record.value?.orderNo;
    processData(whichData).catch((error) => {
      message.error('处理数据时出错：' + error.message || '未知错误');
      return;
    });

    // 查看时禁用表单并修改按钮文字
    if (action.value === 'view') {
      BaseFormApi.setState({
        commonConfig: { disabled: true },
        submitButtonOptions: { show: false },
      });
      modalApi.setState({ showConfirmButton: false });
    } else {
      BaseFormApi.setState({
        commonConfig: { disabled: false },
        submitButtonOptions: { show: '提交' },
      });
      modalApi.setState({ showConfirmButton: true });
    }
  },
  onConfirm() {
    return onSubmit();
  },
  onClosed() {
    // 关闭时重置表单
    BaseFormApi.resetForm();
  },
  onCancel() {
    modalApi.close();
  },
});

/*==============================函数过程===============================*/
// 数据处理函数
let currentCreatedate: Dayjs;
dayjs.extend(customParseFormat);
dayjs.locale('zh-cn');
async function processData(orderNo: any) {
  try {
    if (!orderNo) return new Error('未传递委托单号！');

    let data;
    if (orderNo === 'WOSHIJIADE') {
      data = originalData;
      data.orderDate = dayjs();
    } else {
      const res = await handleOrderdataApi('getInfo', orderNo);
      data = res[0];
      data.orderDate = <Dayjs>dayjs(data.orderDate);
      const startDate = dayjs(data.testCycle.split('～')[0], 'YYYY年MM月DD日', true);
      const endDate = dayjs(data.testCycle.split('～')[1], 'YYYY年MM月DD日', true);
      if (!startDate.isValid() || !endDate.isValid()) {
        return new Error('测试周期日期格式验证失败！');
      }
      data.testCycle = [startDate, endDate];
      currentCreatedate = dayjs(data.createTime);

      // 1转为true，0转为false
      data.subcontractTest = data.subcontractTest === 1;
      data.sampleHandling = data.sampleHandling === 1;
      data.serviceType = data.serviceType === 1;
      data.reportResult = data.reportResult === 1;

      // 处理数组字段
      const fields = ['sampleProp', 'testItems'];
      fields.forEach((item) => {
        if (data[item] && typeof data[item] === 'string') {
          try {
            data[item] = JSON.parse(data[item]);
          } catch (error) {
            console.error(`处理字段 ${item}时出错:`, error);
            throw new Error(`处理字段 ${item}时出错(${error.message || '未知错误1'})`);
          }
        }
      });
    }

    // 表单赋值
    try {
      BaseFormApi.setValues(data);
      return 'ok';
    } catch (error) {
      throw new Error('表单赋值时出错(' + error.message || '未知错误2' + ')');
    }
  } catch (error) {
    throw new Error(error.message || '未知错误3');
  }
}

/*==============================表单事件===============================*/
async function onSubmit() {
  // 验证表单
  const isValid = await BaseFormApi.validate();
  if (!isValid.valid) {
    message.error({ content: '数据填写不完整，请检查！', key: 'beforeSubmit' });
    return;
  }
  // 二次确认
  const confirmRes = await confirmModal('提交确认', '即将提交数据，是否继续？');
  if (!confirmRes) return;

  try {
    // 锁定modal
    modalApi.setState({ loading: true, confirmLoading: true });
    message.loading({
      content: '数据验证处理中，请稍后...',
      duration: 0,
      key: 'beforeSubmit',
    });
    // 延迟0.5秒，确保全局loading生效，防止用户再次操作
    await new Promise((resolve) => setTimeout(resolve, 500));

    const values = toRaw(await BaseFormApi.getValues()); // 必须使用toRaw转换，否则values为Proxy对象，无法序列化

    // 获取编号————修改：直接用当前的orderNo；新增、另存为：获取orderDate对应月份的最大编号
    const orderNo_Date = dayjs(values.orderDate).endOf('month').format('YYYY-MM-DD'); // 获取当前月份的最后一天
    const currentOrderNo =
      action.value === 'edit' ? record.value?.orderNo : await handleOrderdataApi('getInfo', null, orderNo_Date);
    console.log('当前编号：', currentOrderNo);

    // 格式化时间，避免时间格式不一致导致的问题
    values.orderDate = dayjs(values.orderDate).format('YYYY-MM-DD');
    // 转化测试周期
    values.testCycle =
      dayjs(values.testCycle[0]).format('YYYY年MM月DD日') + '～' + dayjs(values.testCycle[1]).format('YYYY年MM月DD日');
    if (action.value === 'new' || action.value === 'saveAs') {
      values.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 登记时间
      values.receiveStatus = 0; // 收样状态
    } else {
      values.createTime = currentCreatedate.format('YYYY-MM-DD HH:mm:ss');
    }
    values.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 更新时间

    // 提交数据
    handleOrderdataApi('submit', currentOrderNo, JSON.stringify(values)).then(() => {
      modalApi.setState({ loading: false, confirmLoading: false });
      message.success({ content: '提交成功', key: 'beforeSubmit', duration: 3 });
      gridApi.value?.reload();
      modalApi.close();
    });
  } catch (error) {
    // console.log(error);
    modalApi.setState({ loading: false, confirmLoading: false });
    message.error({
      content: `提交失败：${error.message}`,
      key: 'beforeSubmit',
    });
  } finally {
    // 重置loading状态
    modalApi.setState({ loading: false, confirmLoading: false });
  }
}

/*==============================其他事件===============================*/

defineExpose(modalApi);
</script>

<template>
  <VbenModal
    :title="action === 'view' ? '查看委托单' : action === 'new' ? '新增委托单' : '编辑委托单'"
    class="w-[90%] h-auto"
  >
    <Card>
      <BaseForm />
    </Card>
  </VbenModal>
</template>
